package com.czt.mail.limit;

/**
 * @author czt
 * @version 1.0
 * @date 2024/8/21 17:06
 * {@desc} 计算器限流/固定窗口   对某个接口a，限定指定时间窗口内(如1s)，请求数不能超过n(1000)
 * 优点:简单粗暴  缺点:限流不平滑，边界处如果有突发流量，导致限流不准确
 */
public class CounterLimiter {
    /**
     *
     */
    //请求个数
    private int counter;

    //阈值
    private final int limitThreshold;

    //时间窗口时长，单位ms
    private final long interval;

    //时间窗口的开始时间
    private long windowStartTime = System.currentTimeMillis();

    public CounterLimiter(int limitThreshold, long interval) {
        this.limitThreshold = limitThreshold;
        this.interval = interval;
    }

    /**
     * @return true:限流，false:通过
     */
    public synchronized boolean limit() {
        long now = System.currentTimeMillis();
        if (now < windowStartTime + interval) {
            if (counter + 1 > limitThreshold) {
                return true;
            }
        }else {
            windowStartTime = now;
            counter = 0;
        }
        counter++;
        return false;
    }
}
